package teacher;

import java.security.SecureRandom;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Random;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.project.trac.R;

import core.modules.DatabaseConnector;
import core.modules.Institute;

public class NewSchedule extends Institute implements OnClickListener {
	
	private Spinner selection_CatalogNumber;
	private Spinner selection_Rooms;
	
	static final int TIME_START = 999;
	static final int TIME_END = 998;
	
	private int hour_s; private int hour_e;
	private int min_s; private int min_e;
	
	private TextView description;
	private TextView passPhrase;
	private EditText section;
	private EditText max;
	
	private CheckBox cb1;
	private CheckBox cb2;
	private CheckBox cb3;
	private CheckBox cb4;
	private CheckBox cb5;
	private CheckBox cb6;
	
	private ArrayList<CheckBox> arrayList_cb = new ArrayList<CheckBox>();
	private List<String> list_day = new ArrayList<String>();
	
	private Button timeStart;
	private Button timeEnd;
	
	private List<String> catalogNumber = new ArrayList<String>();
	private List<String> catalogId = new ArrayList<String>();
	private List<String> catalogDescription = new ArrayList<String>();
	private List<String> rooms = new ArrayList<String>();
	
	private String days;
	private boolean submitted;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.teacher_subjects_create);
		
		description = (TextView) findViewById(R.id.create_text_description);
		passPhrase = (TextView) findViewById(R.id.passPhrase);
		
		timeStart = (Button) findViewById(R.id.btnTimeStart);
		timeEnd = (Button) findViewById(R.id.btnTimeEnd);
		
		section = (EditText) findViewById(R.id.et_create_section);
		max = (EditText) findViewById(R.id.max);
		
		timeStart.setOnClickListener(this);
		timeEnd.setOnClickListener(this);
		
		cb1 = (CheckBox) findViewById(R.id.cb1); cb2 = (CheckBox) findViewById(R.id.cb2); cb3 = (CheckBox) findViewById(R.id.cb3);
		cb4 = (CheckBox) findViewById(R.id.cb4); cb5 = (CheckBox) findViewById(R.id.cb5); cb6 = (CheckBox) findViewById(R.id.cb6);
		
		arrayList_cb.add(cb1); arrayList_cb.add(cb2); arrayList_cb.add(cb3); 
		arrayList_cb.add(cb4); arrayList_cb.add(cb5); arrayList_cb.add(cb6);
		
		
		final Calendar c = Calendar.getInstance();
		hour_s = c.get(Calendar.HOUR_OF_DAY);
		min_s = c.get(Calendar.MINUTE);
		
		// ----------------------------------------------------------	Spinner : Catalog Number
		
		selection_CatalogNumber = (Spinner) findViewById(R.id.sp_catalogNumber);
		selection_CatalogNumber.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				passPhrase.setText(generateCode(6));
				description.setText(catalogDescription.get(position).toString());
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) { }
		}); 
		
		new AsynchronousTask().execute("initialize");
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.teacher, menu);
		return true;
	}
	
	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}
	
	@Override
	public void onClick(View v) {

		switch(v.getId()) {
		
		case R.id.btnTimeStart:
			showDialog(TIME_START);
			break;
		
		case R.id.btnTimeEnd:
			showDialog(TIME_END);
			break;
		
		default: { };
		}
		
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case TIME_START:
			return (new TimePickerDialog(this, timePickerStart, hour_s, min_s,false));
		
		case TIME_END:
			return (new TimePickerDialog(this, timePickerEnd, hour_s, min_s,false));
		}
		return null;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	        case R.id.menu_logout:
	            	new Institute().Logout(this);
	            return true;
	            
	        case R.id.NEW_SCHEDULE:
		            description.setText("");
		            section.setText("");
		            timeStart.setText("Start");
		            timeEnd.setText("End");
		            passPhrase.setText(generateCode(6));
	            return true; 
	            
	        case R.id.SAVE_AND_NEW_SCHEDULE:
	        	
	        	if (description.getText().toString().length() == 0) {
	        		description.setError("Field is required!");
	        	}
	        	
	    		for (CheckBox cb : arrayList_cb) {
	        		if (cb.isChecked()) {
	        			list_day.add(cb.getText().toString());
	        		}
	        	}
	    		
	    		StringBuilder day = new StringBuilder(list_day.toString());
	        	days = day.subSequence(1, day.length()-1).toString();

	        	if ((hour_e - hour_s) >= 1) {
	        		new AsynchronousTask().execute("submit");
	        	} else {
	        		//TODO: validation needed to set day.
	        		Toast.makeText(getApplicationContext(), 
							"Minimum class time is 60 minutes", Toast.LENGTH_SHORT).show();
	        	}
	        	
	        	return true;
	        	
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	
	private String generateCode(int length) {
		Random rnd = new SecureRandom();
		String seed = "abcdefghjkmnopqrstuvwxyz1234567890ABCDEFGHJKMNPOQRSTUVWXYZ";
		String code = "";
		
		for (int i = 0; i < length; i++) {
			int index = (int) (rnd.nextDouble() * seed.length());
			code += seed.substring(index, index + 1);
		}
		
		return code;
	}
	
	private TimePickerDialog.OnTimeSetListener timePickerStart =  new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int selectedHour, int selectedMinute) {
			hour_s = selectedHour;
			min_s = selectedMinute;
			timeStart.setText(new StringBuilder().append(padding_str(hour_s)).append(":").append(padding_str(min_s)));
		}
	};
	
	private TimePickerDialog.OnTimeSetListener timePickerEnd =  new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int selectedHour, int selectedMinute) {
			hour_e = selectedHour;
			min_e = selectedMinute;
			timeEnd.setText(new StringBuilder().append(padding_str(hour_e)).append(":").append(padding_str(min_e)));
		}
	};
 
	private static String padding_str(int c) {
		if (c >= 10)
		   return String.valueOf(c);
		else
		   return "0" + String.valueOf(c);
	}
	
	private class AsynchronousTask extends AsyncTask<String, String, String> {
		
		ArrayAdapter<String> arrayAdapter_Catalog;
		ArrayAdapter<String> arrayAdapter_Rooms;
		
		HashMap<String, String> m;
		
		ArrayList<HashMap<String, String>> arrayList = new ArrayList<HashMap<String, String>>();
		
		ProgressDialog dialog;

		String KEY_CAT = "k1";
		String KEY_SUBJECT_ID = "k8";
		String KEY_ROOMS = "k3";

		ResultSet rs;

		protected void onPreExecute() {
			super.onPreExecute();
			dialog = new ProgressDialog(NewSchedule.this);
			dialog.setTitle("Please Wait");
			dialog.setMessage("Preparing form...");
			dialog.setIndeterminate(true);
			dialog.setCancelable(true);
			dialog.show();

		}

		@Override
		protected String doInBackground(String... args) {
			
			try {
				if (args[0].equalsIgnoreCase("initialize")) {
					if (rs == null) {
						rs = DatabaseConnector.getStatement().executeQuery("select * from curriculum");
						while (rs.next()) {
							m = new HashMap<String, String>();
							m.put(KEY_CAT, rs.getString("catalognumber"));
							m.put(KEY_SUBJECT_ID, rs.getString("id"));
							arrayList.add(m);
								
							catalogNumber.add(rs.getString("catalognumber"));
							catalogId.add(rs.getString("id"));
							catalogDescription.add(rs.getString("catalogtitle"));
						}
						rs.close();
					}
					
					if (rs.isClosed()) {
						rs = DatabaseConnector.getStatement().executeQuery("select * from rooms");
						while (rs.next()) {
							m = new HashMap<String, String>();
							m.put(KEY_ROOMS, rs.getString("bldg").concat(rs.getString("number")));
							arrayList.add(m);
								
							rooms.add(rs.getString("bldg").concat(rs.getString("number")));
						}
						
						rs.close();
					}
					
				} // --- end initialize
				
				
				if (args[0].equalsIgnoreCase("submit")) {
						DatabaseConnector.setPreparedStatement(
						"INSERT INTO schedule (uid, cid, section, room, days, time, code, max) VALUES (?,?,?,?,?,?,?,?)");
						PreparedStatement pps = DatabaseConnector.getPreparedStatement();
							pps.setInt(1, getUserID());
							pps.setInt(2, Integer.valueOf(catalogId.get(catalogNumber.indexOf(selection_CatalogNumber.getSelectedItem().toString()))));
							pps.setString(3, section.getText().toString().toUpperCase(Locale.getDefault()));
							pps.setString(4, selection_Rooms.getSelectedItem().toString());
							pps.setString(5, days.toString());
							
							//FIXME: ensure human readable encoding in database; get AM or PM time
							pps.setString(6, timeStart.getText().toString().concat(" - ").concat(timeEnd.getText().toString()).toString());
							pps.setString(7, passPhrase.getText().toString());
							
							if (max.getText().toString().length() == 0 ) {
								pps.setInt(8, 40);
							} else {
								pps.setInt(8, Integer.valueOf(max.getText().toString()));
							}
							
							submitted = true;
							pps.executeUpdate();
							pps.close();

				}	// --- end new schedule
			
			} catch (SQLException e) {
				DatabaseConnector.Logger(getClass(), "doInBackground", e);
			}
			
			return null;
		}
		
		protected void onPostExecute(String postExecute) {
			dialog.dismiss();

			runOnUiThread(new Runnable() {

				public void run() {
					arrayAdapter_Catalog = new ArrayAdapter<String>(NewSchedule.this, android.R.layout.simple_spinner_item, catalogNumber);
						arrayAdapter_Catalog.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
						
					arrayAdapter_Rooms = new ArrayAdapter<String>(NewSchedule.this, android.R.layout.simple_spinner_item, rooms);
						arrayAdapter_Rooms.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					
					selection_CatalogNumber = (Spinner) findViewById(R.id.sp_catalogNumber);
						selection_CatalogNumber.setAdapter(arrayAdapter_Catalog);
						selection_CatalogNumber.setPrompt("Select below");
						
					selection_Rooms = (Spinner) findViewById(R.id.sp_rooms);
						selection_Rooms.setAdapter(arrayAdapter_Rooms);
						selection_Rooms.setPrompt("Select below");
				}
			});
			
			if (submitted) {
				Toast.makeText(getApplicationContext(), "Schedule was set.", Toast.LENGTH_SHORT).show();
				NewSchedule.this.finish();
			}
		}
		
	}

}